package com.ml4ai.backend.services.providers

import java.util

import com.google.common.collect.Lists
import com.google.gson.{Gson, GsonBuilder, JsonParser}
import com.ml4ai.backend.services.{DbMapService, RabbitmqService, StreamSourceService, UserService}
import com.ml4ai.backend.services.capability.{Command, CommandReceiver}
import com.ml4ai.core.stack.elasticsearch.{BoolBuilderCreator, ElasticSearchAgent}
import com.ml4ai.core.stack.mq.RabbitMQAgent
import javax.annotation.PostConstruct
import org.springframework.beans.factory.annotation.{Autowired, Value}
import org.springframework.stereotype.Service

import scala.collection.JavaConverters._

@Service
class LoadAbstractsCommandReceiver extends CommandReceiver {

  @Value("${elasticsearch.servers}") private val esServers: String = null
  @Value("${elasticsearch.cluster}") private val cluster: String = null
  @Autowired var rabbitmqService: RabbitmqService = null
  private var elasticsearch: ElasticSearchAgent = null
  private var rabbitMQAgent: RabbitMQAgent = null
  private var googleJsonWrapperBean: Gson = null
  private var jsonParser: JsonParser = null

  @PostConstruct def init(): Unit = {
    elasticsearch = ElasticSearchAgent.builder.esServers(esServers).esCluster(cluster).build
    rabbitMQAgent = rabbitmqService.getRabbitMQAgent
    jsonParser = new JsonParser
    val googleJsonWrapperBuilder = new GsonBuilder
    googleJsonWrapperBuilder.serializeNulls
    googleJsonWrapperBuilder.setDateFormat("yyyy-MM-dd")
    googleJsonWrapperBean = googleJsonWrapperBuilder.create
  }

  override def getSupport(): String = "loadAbstracts"

  override def execute(command: Command): Unit = {
    val start = command.get("start").toInt
    val size = command.get("size").toInt
    val parameter = googleJsonWrapperBean.fromJson(command.get("parameter"), classOf[util.Map[String, AnyRef]])
    val searchRequestBuilder = elasticsearch.getClient.prepareSearch("app-contents").setTypes("default")
    val searchResponse = searchRequestBuilder.setQuery(BoolBuilderCreator.createBoolQueryBuilder(parameter)).setFrom(start).setSize(size).get
    val list = Lists.newArrayList(searchResponse.getHits.iterator()).asScala.map(hit => hit.getSourceAsMap()).asJava
    val response = new java.util.HashMap[String, AnyRef]
    response.put("code", "200")
    response.put("msg", "摘取成功")
    response.put("data", list)
    rabbitMQAgent.produceText("", command.getCallback(), googleJsonWrapperBean.toJson(response), false)
  }

}
